package com.cloudwise.thread;

import com.cloudwise.util.TreeUtil;
import org.springframework.util.StopWatch;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @author ：Teacher陈
 * @date ：Created in 2021/1/5 11:29
 * @description：实现callable接口
 * @modified By：
 * @version: 1
 */
public class ImplementsCallable  implements Callable<String> {
    private String ip;

    public ImplementsCallable(String ip) {
        this.ip = ip;
    }

    /**
     * @create by: Teacher陈
     * @description: 类似于run方法，但是有返回值
     * @create time: 2021/1/5 11:30
     * @return String
     */
    @Override
    public String call() throws Exception {
        boolean checkHost = TreeUtil.checkHost(ip);
        //如果ip能联通，返回ip，否则返回null
        if(checkHost){
            return ip;
        }
        return null;
    }

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        StopWatch sw = new StopWatch();
        sw.start();
        List<FutureTask<String> > tasks= new ArrayList<>();
        for (int i = 1; i <255 ; i++) {
            String ip="192.168.31."+i;
            //创建一个多线程对象
            ImplementsCallable  implementsCallable= new ImplementsCallable(ip);
            //futureTask  对象获取返回值
            FutureTask<String>  task= new FutureTask<>(implementsCallable);
            tasks.add(task);
            //启动多线程
            new  Thread(task).start();
        }
        //上面的代码启动了254个线程,封装到teasks集合中，1，等待所有的线程结束
        while(true){
            Thread.sleep(100);
            int count=0;
            for (FutureTask<String> tempTask : tasks) {
                //判断线程是否结束，如果结束，计数器加1
                if(tempTask.isDone()){
                    count++;
                }
            }
            //如果所有的线程都执行完
            if(count==tasks.size()){
                break;
            }
        }
        sw.stop();

        System.out.println("====================总花费时间"+(sw.getTotalTimeMillis()));
        System.out.println("====================可以联通的机器ip=========================");
        //2：获取所有线程执行的返回值
        for (FutureTask<String> task : tasks) {
            if(task.get()!=null){
                System.out.println(task.get());
            }
        }
    }
}
